package com.example.calendar.ui.screens.settings

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Brush
import androidx.compose.material.icons.filled.DarkMode
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.Notifications
import androidx.compose.material.icons.filled.Schedule
import androidx.compose.material.icons.filled.Sync
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Divider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import com.example.calendar.ui.theme.ThemeManager
import kotlinx.coroutines.launch

/**
 * Screen for displaying and modifying app settings
 */
@Composable
fun SettingsScreen(
    navController: NavController,
    viewModel: SettingsViewModel = hiltViewModel()
) {
    // Initialize theme manager
    val context = LocalContext.current
    val themeManager = remember { ThemeManager(context) }
    val themeMode by themeManager.themeMode.collectAsState(initial = ThemeManager.ThemeMode.SYSTEM)
    val scope = rememberCoroutineScope()
    
    // State for theme selection dialog
    var showThemeDialog by remember { mutableStateOf(false) }
    
    Scaffold { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .verticalScroll(rememberScrollState())
        ) {
            // Appearance settings section
            SettingsSectionHeader(title = "Appearance")
            
            // Theme mode selector
            SettingItem(
                title = "Theme Mode",
                description = when (themeMode) {
                    ThemeManager.ThemeMode.SYSTEM -> "Follow system theme"
                    ThemeManager.ThemeMode.LIGHT -> "Light theme"
                    ThemeManager.ThemeMode.DARK -> "Dark theme"
                },
                icon = Icons.Default.DarkMode,
                onClick = { showThemeDialog = true }
            )
            
            SettingItem(
                title = "Theme Customization",
                description = "Customize app colors and appearance",
                icon = Icons.Default.Brush,
                onClick = { /* Will be implemented in the future */ }
            )
            
            Divider(modifier = Modifier.padding(vertical = 8.dp))
            
            // Calendar settings section
            SettingsSectionHeader(title = "Calendar")
            
            val firstDayOfWeek by viewModel.firstDayOfWeek.collectAsState(initial = 0)
            SettingItem(
                title = "First Day of Week",
                description = when(firstDayOfWeek) {
                    1 -> "Monday"
                    2 -> "Tuesday"
                    3 -> "Wednesday"
                    4 -> "Thursday"
                    5 -> "Friday"
                    6 -> "Saturday"
                    else -> "Sunday"
                },
                icon = Icons.Default.Schedule,
                onClick = { viewModel.showDayOfWeekPicker() }
            )
            
            // If day of week picker is visible
            if (viewModel.showDayOfWeekPickerDialog) {
                DayOfWeekPickerDialog(
                    selectedDay = firstDayOfWeek,
                    onDaySelected = { day -> 
                        scope.launch {
                            viewModel.setFirstDayOfWeek(day)
                            viewModel.hideDayOfWeekPicker()
                        }
                    },
                    onDismiss = { viewModel.hideDayOfWeekPicker() }
                )
            }
            
            Divider(modifier = Modifier.padding(vertical = 8.dp))
            
            // Notifications settings section
            SettingsSectionHeader(title = "Notifications")
            
            val notificationsEnabled by viewModel.notificationsEnabled.collectAsState(initial = false)
            ToggleSetting(
                title = "Event Reminders",
                description = "Receive notifications for upcoming events",
                icon = Icons.Default.Notifications,
                checked = notificationsEnabled,
                onCheckedChange = { 
                    scope.launch {
                        viewModel.setNotificationsEnabled(it)
                    }
                }
            )
            
            Divider(modifier = Modifier.padding(vertical = 8.dp))
            
            // Sync settings section
            SettingsSectionHeader(title = "Synchronization")
            
            val syncEnabled by viewModel.syncEnabled.collectAsState(initial = false)
            ToggleSetting(
                title = "Auto Sync",
                description = "Automatically sync your calendar data",
                icon = Icons.Default.Sync,
                checked = syncEnabled,
                onCheckedChange = { 
                    scope.launch {
                        viewModel.setSyncEnabled(it)
                    }
                }
            )
            
            Divider(modifier = Modifier.padding(vertical = 8.dp))
            
            // About section
            SettingsSectionHeader(title = "About")
            
            SettingItem(
                title = "Version",
                description = viewModel.appVersion,
                icon = Icons.Default.Info,
                onClick = { /* No action needed */ }
            )
            
            // Add bottom spacing
            Spacer(modifier = Modifier.height(80.dp))
        }
    }
    
    // Theme selection dialog
    if (showThemeDialog) {
        ThemeModeDialog(
            currentMode = themeMode,
            onModeSelected = { mode ->
                scope.launch {
                    themeManager.setThemeMode(mode)
                    showThemeDialog = false
                }
            },
            onDismiss = { showThemeDialog = false }
        )
    }
}

@Composable
fun ThemeModeDialog(
    currentMode: ThemeManager.ThemeMode,
    onModeSelected: (ThemeManager.ThemeMode) -> Unit,
    onDismiss: () -> Unit
) {
    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("Choose Theme") },
        text = {
            Column {
                ThemeModeOption(
                    title = "System Default",
                    selected = currentMode == ThemeManager.ThemeMode.SYSTEM,
                    onClick = { onModeSelected(ThemeManager.ThemeMode.SYSTEM) }
                )
                ThemeModeOption(
                    title = "Light",
                    selected = currentMode == ThemeManager.ThemeMode.LIGHT,
                    onClick = { onModeSelected(ThemeManager.ThemeMode.LIGHT) }
                )
                ThemeModeOption(
                    title = "Dark",
                    selected = currentMode == ThemeManager.ThemeMode.DARK,
                    onClick = { onModeSelected(ThemeManager.ThemeMode.DARK) }
                )
            }
        },
        confirmButton = {
            TextButton(onClick = onDismiss) {
                Text("Cancel")
            }
        }
    )
}

@Composable
fun ThemeModeOption(
    title: String,
    selected: Boolean,
    onClick: () -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clickable(onClick = onClick)
            .padding(vertical = 8.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        RadioButton(
            selected = selected,
            onClick = onClick
        )
        
        Spacer(modifier = Modifier.width(8.dp))
        
        Text(
            text = title,
            style = MaterialTheme.typography.bodyLarge
        )
    }
}

@Composable
fun DayOfWeekPickerDialog(
    selectedDay: Int,
    onDaySelected: (Int) -> Unit,
    onDismiss: () -> Unit
) {
    val days = listOf("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
    
    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("First Day of Week") },
        text = {
            Column {
                days.forEachIndexed { index, day ->
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .clickable { onDaySelected(index) }
                            .padding(vertical = 8.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        RadioButton(
                            selected = selectedDay == index,
                            onClick = { onDaySelected(index) }
                        )
                        
                        Spacer(modifier = Modifier.width(8.dp))
                        
                        Text(
                            text = day,
                            style = MaterialTheme.typography.bodyLarge
                        )
                    }
                }
            }
        },
        confirmButton = {
            TextButton(onClick = onDismiss) {
                Text("Cancel")
            }
        }
    )
}

@Composable
fun SettingsSectionHeader(title: String) {
    Text(
        text = title,
        style = MaterialTheme.typography.titleMedium,
        color = MaterialTheme.colorScheme.primary,
        fontWeight = FontWeight.Bold,
        modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)
    )
}

@Composable
fun SettingItem(
    title: String,
    description: String,
    icon: ImageVector,
    onClick: () -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clickable(onClick = onClick)
            .padding(horizontal = 16.dp, vertical = 12.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Icon(
            imageVector = icon,
            contentDescription = null,
            tint = MaterialTheme.colorScheme.onSurfaceVariant
        )
        
        Spacer(modifier = Modifier.width(16.dp))
        
        Column(modifier = Modifier.weight(1f)) {
            Text(
                text = title,
                style = MaterialTheme.typography.bodyLarge,
                color = MaterialTheme.colorScheme.onSurface
            )
            
            Text(
                text = description,
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }
    }
}

@Composable
fun ToggleSetting(
    title: String,
    description: String,
    icon: ImageVector,
    checked: Boolean,
    onCheckedChange: (Boolean) -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clickable { onCheckedChange(!checked) }
            .padding(horizontal = 16.dp, vertical = 12.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Icon(
            imageVector = icon,
            contentDescription = null,
            tint = MaterialTheme.colorScheme.onSurfaceVariant
        )
        
        Spacer(modifier = Modifier.width(16.dp))
        
        Column(modifier = Modifier.weight(1f)) {
            Text(
                text = title,
                style = MaterialTheme.typography.bodyLarge,
                color = MaterialTheme.colorScheme.onSurface
            )
            
            Text(
                text = description,
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }
        
        Switch(
            checked = checked,
            onCheckedChange = onCheckedChange
        )
    }
}

@Preview(showBackground = true)
@Composable
fun SettingsScreenPreview() {
    SettingsScreen(navController = rememberNavController())
} 